#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2016 lizongzhe
#
# Distributed under terms of the MIT license.
import urllib
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
import logging
from esr_parser.core import get_item_id
from esr_parser.utils import func
logger = logging.getLogger(__name__)


class Order(object):
    general = ''
    sales = '_deal'
    credit = '_credit'
    pricing_asc = 'price'
    pricing_desc = '_price'


class Rank_Task(object):
    driver = None

    def __init__(self, driver, keyword, order_by=Order.general, tm_only=False, limit=604):
        self.driver = driver
        self.keyword = keyword
        self.limit = limit
        self.order_by = order_by
        self.tm_only = tm_only

    @func.auto_retry(3)
    def process(self):
        keyword = self.keyword
        result_items = []
        result_right_items = []
        result_bottom_items = []
        self.search_items()
        while len(result_items) < self.limit:
            self.load_page()
            meta = {"page_num": self.get_current_page()}
            items, right_items, bottom_items = self.parse_page(meta)
            result_items += items
            result_right_items += right_items
            result_bottom_items += bottom_items
            self.next_page()
        return result_items, result_right_items, result_bottom_items

    search_page = 'https://world.taobao.com/search/search.htm?&_input_charset=utf-8&q={}&sort={}&tmall={}'

    @func.auto_retry(3)
    def search_items(self):
        logger.debug('start search items')
        if self.tm_only:
            tm_only = 1
        else:
            tm_only = ''

        page_url = self.search_page.format(urllib.quote_plus(
            self.keyword.encode('utf-8')), self.order_by, tm_only)
        self.driver.get(page_url)

    def next_page(self):
        current_page = self.get_current_page()
        next_page = current_page + 1
        logger.debug('start next page {}'.format(next_page))

        next_page_bottom = self.driver.find_element_by_css_selector(
            '.page-icon.next')
        next_page_bottom.click()
        WebDriverWait(self.driver, 5).until(
            lambda x: self.get_current_page() == next_page)

    @func.auto_retry(3)
    def get_current_page(self):
        page = self.driver.find_element_by_css_selector(
            '#list-page .active').text
        return int(page)

    @func.auto_retry(3)
    def load_page(self):
        logger.debug('start load page')
        driver = self.driver
        foot_elem = driver.find_element_by_css_selector('.footer-hd')
        # scroll down
        actions = ActionChains(driver)
        actions.move_to_element(foot_elem)
        actions.perform()
        actions.move_to_element(foot_elem)
        actions.perform()
        WebDriverWait(self.driver, 5).until(lambda x: len(
            x.find_elements_by_css_selector('#list-p4p-bottom .item')) > 1)

    @func.auto_retry(3)
    def parse_page(self, meta={}):
        logger.debug('parse page')
        driver = self.driver
        main_items = driver.find_elements_by_css_selector(
            '#list-itemList .item')
        right_items = driver.find_elements_by_css_selector(
            '#list-p4p-aside .item')
        bottom_items = driver.find_elements_by_css_selector(
            '#list-p4p-bottom .item')

        items = self.parse_items(main_items, meta)
        right_items = self.parse_items(right_items, meta)
        bottom_items = self.parse_items(bottom_items, meta)
        return items, right_items, bottom_items

    @func.auto_retry(3)
    def parse_items(self, items, meta={}):
        result = []
        for index, item in enumerate(items):
            item_info = {}
            item_info['is_tm'] = bool(
                item.find_elements_by_css_selector('.icons a[href*=tmall]'))
            item_info['page_set'] = index
            comment_elem = item.find_element_by_css_selector(
                '.title.child-component a')
            item_info['pro_name'] = comment_elem.text
            paid_elem = item.find_elements_by_css_selector('.paid-num a')
            item_info['month_pays'] = paid_elem and paid_elem[0].text or None
            item_info['price'] = item.find_element_by_css_selector(
                '.g_price strong').text
            item_info['pro_url'] = comment_elem.get_attribute('href')
            item_info['pro_img_url'] = item.find_element_by_css_selector(
                'img').get_attribute('src')
            shop_elem = item.find_elements_by_css_selector('.seller .nick')
            item_info['shop_name'] = shop_elem and shop_elem[0].text or ""

            try:
                item_info['auction_num_id'] = get_item_id(item_info['pro_url'])
            except:
                item_info['auction_num_id'] = None

            item_info.update(meta)

            result.append(item_info)

        return result
